using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Reflection;

namespace wtupdater
{
	class Program
	{
		[STAThread]
		static void Main(string[] args)
		{
            string workfolder = Path.GetDirectoryName(args[0]);
            //Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string updatefolder = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "WorkTime"), "update");
			string wtprocessname = "worktime";
			string wtprocessfile = "WTUPDATER.EXE";
			string[] filesList = new string[0];

			//updates to process
			if (Directory.Exists(updatefolder))
			{
				// get updates list
				try
				{
					filesList = Directory.GetFiles(updatefolder);
				}
				catch (Exception e)
				{
					Console.WriteLine(e.Message);
				}

				// kill worktime process
				while ((Process.GetProcessesByName(wtprocessname).Length > 0))
				{
                    foreach (Process p in Process.GetProcessesByName(wtprocessname))
                    {
                        p.Kill();
						p.WaitForExit();
                    }
				}

				foreach (string filein in filesList)
				{
					string file = Path.GetFileName(filein);

					if (file.ToUpper() == wtprocessfile.ToUpper())
						continue;

					try
					{
						File.Delete(Path.Combine(workfolder, file));
						File.Copy(filein, Path.Combine(workfolder, file));
						File.Delete(filein);
					}
					catch (Exception e)
					{
						Console.WriteLine(e.Message);
					}
				}
			}

			try
			{
				if (Directory.Exists(updatefolder))
					Directory.Delete(updatefolder);
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
			}
			
			try
			{
				Process.Start(Path.Combine(workfolder, wtprocessname + ".exe"));
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
			}
		}
	}
}
